/**
 * Created by wei on 16-8-10.
 */
angular.module("starter.projectTrackController", ['ngLoadScript'])
    .controller("ProjectTrackCtrl", function ($scope, $rootScope, $user, $task, $loading, $lookup, $region, $log, $state, $compile, $timeout, $ionicScrollDelegate) {
        // 初始化
        $scope.vm = { search: '', showFilters: false, choiceFilter: '', showFilterTag: false, isIos: false, showContent: false };
        $scope.items = [];
        $scope.filterItems = [];
        $rootScope.isProjectTrackContent = false;

        if (ionic.Platform.isIOS()) {
            $scope.vm.isIos = true;
        }

        $scope.user = $user.getCurrentUserSync();

        $scope.choiceFilter = function (type) {
         $scope.vm.choiceFilter = type;
         $scope.vm.showFilterTag = true;
         $scope.vm.showFilters = false;
         $rootScope.devinHideTabs = false;
         $ionicScrollDelegate.$getByHandle('my-handle').resize();
       }

        $scope.hideFilterTag = function () {
         $scope.vm.choiceFilter = '';
         $scope.vm.showFilterTag = false;
         $ionicScrollDelegate.$getByHandle('my-handle').resize();
      }

        //显示筛选条件
        $scope.showFilters = function () {
            $scope.vm.showFilters = !$scope.vm.showFilters;
            $rootScope.devinHideTabs = !$rootScope.devinHideTabs;
        }

        $lookup.getWithlookupType('PROJECT_STATUS').executeSuccess(function (lookup) {
            $scope.filterItems = lookup;
        });

        // 下拉刷新
        $scope.doRefresh = function (userId, listType) {
            $task.getTaskList(userId, listType).success(function (data) {
              $scope.items = [];
              if (data.code == "SUCCESS") {
                    angular.forEach(data.data, function (project) {
                        $lookup.getWithLookupCode(project.status).executeSuccess(function (lookup) {
                            project.statusDesc = lookup.lookupMeaning;
                        });
                        var region = $region.getWithRegion(project.regionCode);
                        project.regionDesc = '' + region.provinceName + region.cityName + region.regionName;
                        $scope.items.push(project);
                    })
                } else {
                    $loading.showError("网络出了一点小问题,请稍后再试")
                }
            }).error(function (data) {
                $loading.showError("加载数据失败");
            });
            $scope.isCanLoadMore = true;
            $scope.$broadcast('scroll.refreshComplete');
          $ionicScrollDelegate.$getByHandle('my-handle').resize();

        }

        $scope.doRefresh($scope.user.userId, "PROJECT_TRACK");

        //搜索
        $scope.projectFilter = function (item) {
            // 判断搜索内容
            if ($scope.vm.search != "") { //空
                if ((!angular.isUndefined(item.projectNumber) && item.projectNumber.indexOf($scope.vm.search) >= 0)//项目编号
                    || (!angular.isUndefined(item.statusDesc) && item.statusDesc.indexOf($scope.vm.search) >= 0) //状态
                    || (!angular.isUndefined(item.customerName) && item.customerName.indexOf($scope.vm.search) >= 0) //客户名称
                    || (!angular.isUndefined(item.contacts) && item.contacts.indexOf($scope.vm.search) >= 0) //联系人
                    || (!angular.isUndefined(item.contactsTel) && item.contactsTel.indexOf($scope.vm.search) >= 0) //联系电话
                    || (!angular.isUndefined(item.address) && item.address.indexOf($scope.vm.search) >= 0)) { //地址 //经销商 //安装商
                    return true;
                } else {
                    return false;
                }
            } else {
                return true;
            }
        }

        var projectContent = document.getElementById('projectContentId');
        //content opations
        var contentOpations = {
            animateType: 'slideIn',    //动画类型
            contentBgOpacity: '.7',   //背景透明度
            contentBgcolor: '#fff',   //背景颜色
            animateDuration: '.5s',  //动画时常
            templateUrl: 'templates/project-track/project-track-content.html'    //模版url
        };

        //content init
        var defineContent = new DefineContent(contentOpations);
        $scope.forwardTrackContent = function (item) {

            window.currentPorjectInfo = item;

            //return [0]content  [1]contentBg
            $scope.vm.contents = defineContent.addInto(projectContent);

          $scope.vm.trackScope = $scope.$$childHead.$new() ;

            $timeout(function () {
                var element = $compile($scope.vm.contents[0])($scope.vm.trackScope);
                $scope.vm.showContent = true;
                $rootScope.devinHideTabs = true;

            }, 300)

        };

        $scope.$on("hideContent", function (event) {
          $scope.hideContent();
        })

      $scope.hideContent = function () {
        $timeout(function () {
          $rootScope.isProjectTrackContent = false;
          $rootScope.isProjectTract = false;
          $timeout(function(){
            $scope.vm.trackScope.$destroy();
          },1000);
          defineContent.deleteSelf();
          $rootScope.defeineContentLazyLoad = false;
          $scope.vm.showContent = false;
          $rootScope.devinHideTabs = false;
        }, 300);
      };
    })
    .controller("ProjectTrackContentCtrl", function ($scope, $rootScope, $ionicHistory, ENV, $state, $user, $dfHttp, $stateParams, $ionicSlideBoxDelegate, $ionicScrollDelegate, $timeout) {
        // $scope.$on("$ionicView.beforeEnter", function () {
        $scope.curStyle = 0;
        $scope.curSubStyle = 0;
        $scope.navi = {
            'currentIndex': 0
        }
        $scope.vm = { 'scrollHeight': 1000 };
        $rootScope.defeineContentLazyLoad = false;
        $scope.vm.scrollHeight = window.screen.availHeight - 178;
        $rootScope.isProjectTrackContent = true;
        $rootScope.isProjectTract = true;

        $timeout(function () {
            $rootScope.defeineContentLazyLoad = true;
        }, 1000);

        $scope.projectInfo = {};
        $scope.projectInfo = window.currentPorjectInfo;
        window.currentProjectId = $scope.projectInfo.projectId;
        $scope.logs = {};


        $scope.backToTask = function () {
            $ionicHistory.goBack()
        };

        var isDragging = false;
        $scope.onTouchThis = function () {
            isDragging = false;
            $ionicSlideBoxDelegate.enableSlide(false);
            $ionicSlideBoxDelegate.$getByHandle('slide-box').enableSlide(false);
        };
        $scope.onDragThis = function (e) {

            if (isDragging) {
                return;
            } else {
                isDragging = true;
                $ionicSlideBoxDelegate.$getByHandle('slide-box').enableSlide(true);
            }

        };

        $scope.progressInfo = { 'point': 0, 'isOver': false, pointImg: [], textClass: [], pointActiveClass: [], lineClass: [] };
        //改变进度条
        var tag_pt = $scope.projectInfo.tag;
        if (!tag_pt) {
            tag_pt = { length: 0 };
        }
        if (tag_pt.length == 1) {
            //实心
            $scope.progressInfo.isOver = true;
            $scope.progressInfo.point = tag_pt;

            for (var i = 0; i < 6; i++) {
                if (i < tag_pt) {
                    $scope.progressInfo.textClass.push('track-text-high');
                    $scope.progressInfo.pointImg.push('end');
                    $scope.progressInfo.lineClass.push('');
                } else if (i == tag_pt) {
                    $scope.progressInfo.textClass.push('track-text-high');
                    $scope.progressInfo.pointImg.push('check');
                    $scope.progressInfo.lineClass.push('track-line-ing');
                } else {
                    $scope.progressInfo.pointImg.push('wait');
                    $scope.progressInfo.textClass.push('');
                    $scope.progressInfo.lineClass.push('track-line-ing');
                }

                if (tag_pt == 0) {
                    $scope.progressInfo.pointImg[0] = 'wait';
                }
            }

        } else {
            //空心
            tag_pt = parseInt(tag_pt);
            $scope.progressInfo.isOver = false;
            $scope.progressInfo.point = tag_pt;

            for (var i = 0; i < 6; i++) {
                if (i < tag_pt) {
                    $scope.progressInfo.textClass.push('track-text-high');
                    $scope.progressInfo.pointImg.push('end');
                    $scope.progressInfo.lineClass.push('');
                } else if (i == tag_pt) {
                    $scope.progressInfo.textClass.push('track-text-high');
                    $scope.progressInfo.pointImg.push('uncheck');
                    $scope.progressInfo.lineClass.push('track-line-ing');
                } else {
                    $scope.progressInfo.textClass.push('');
                    $scope.progressInfo.pointImg.push('wait');
                    $scope.progressInfo.lineClass.push('track-line-ing');
                }

            }
        }

        $user.getCurrentUser().executeSuccess(function (user) {
            //$scope.project.projectId
            $dfHttp.get('api/others/getLoggedInformation.json', { 'projectId': $scope.projectInfo.projectId, 'userId': user.userId }).success(function (data) {
                if (data.code == 'SUCCESS') {
                    $scope.logs = data.data;
                }
            });
        });

        $scope.activeNav = function ($event) {
            var currentElem = $event.target;
            var parentElem = document.getElementById("design-nav-scroll");
            var index = 0;
            for (var i = 0; i < parentElem.children.length; i++) {
                if (currentElem == parentElem.children[i]) {
                    $scope.curStyle = i;
                    $scope.navi.currentIndex = i;
                    currentElem.className = 'active';
                    //console.log(i);
                } else {
                    parentElem.children[i].className = "";
                }
                var sildeBox = $ionicSlideBoxDelegate.$getByHandle('slide-box');
                if ($scope.curStyle < sildeBox.slidesCount()) {
                    sildeBox.slide($scope.curStyle, 500);
                    sildeBox.update();
                }
            }
            if ($scope.curStyle > 2) {
                $ionicScrollDelegate.$getByHandle('nav-scroll').scrollTo(($scope.curStyle - 2) * 80, 0, true);
            }
            if ($scope.curStyle <= 2) {
                $ionicScrollDelegate.$getByHandle('nav-scroll').scrollTop(true);
            }
        }

        $scope.activeSlide = function (index) {
            $scope.navi.currentIndex = index;
            var parentElem = document.getElementById("design-nav-scroll");
            for (var i = 0; i < parentElem.children.length; i++) {
                if (index == i) {
                    $scope.curStyle = i;
                    var currentElem = parentElem.children[i];
                    currentElem.className = 'active';
                    //console.log(i);
                } else {
                    parentElem.children[i].className = "";
                }
            }

            var sildeBox = $ionicSlideBoxDelegate.$getByHandle('slide-box');
            sildeBox.slide($scope.curStyle, 500);
            sildeBox.update();
            if ($scope.curStyle > 2) {
                $ionicScrollDelegate.$getByHandle('nav-scroll').scrollTo(($scope.curStyle - 2) * 80, 0, true);
            }
            if ($scope.curStyle <= 2) {
                $ionicScrollDelegate.$getByHandle('nav-scroll').scrollTop(true);
            }
        }

      $scope.vm.width = 100;
        // });

      $scope.$on('$includeContentLoaded', function () {
        $timeout(function () {
          $scope.vm.width -= 0.1;
          $scope.vm.scrollHeight = window.screen.availHeight - 178;
        }, 30);
      });
    })
    .controller("ProjectLogCtrl", function ($scope, $rootScope, $state, $user, $dfHttp, $stateParams, $ionicHistory, $ionicSlideBoxDelegate, $ionicScrollDelegate, $timeout) {
        $scope.project = $stateParams.args;
        $scope.vm = { noData: false };
        $user.getCurrentUser().executeSuccess(function (user) {
            //$scope.project.projectId
            $dfHttp.get('api/others/getLoggedInformation.json', { 'projectId': angular.isUndefined($scope.project) ? window.currentPorjectInfo.projectId : $scope.project.projectId, 'userId': user.userId }).success(function (data) {
                if (data.code == 'SUCCESS') {

                    $scope.logs = [];
                    for (var i = 0; i < data.data.length; i++) {
                        var spTime = data.data[i].creationDate.split(' ');
                        $scope.logs.push({ disDate: spTime[0], disTime: spTime[1], creatorName: data.data[i].creatorName, logMsg: data.data[i].logMsg });
                    }

                    if ($scope.logs.length == 0) {
                        $scope.vm.noData = true;
                    }
                }
            });
        });

      $scope.$on("backToLast", function () {
        $scope.backToLast();
      });

        $scope.backToLast = function () {
            $rootScope.devinHideTabs = false;
            window.currentProjectId = '';
            $ionicHistory.goBack();
        }
    })

